package com.vnaloha.common.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.vnaloha.common.dao.GalleryDAO;
import com.vnaloha.common.model.Gallery;
import com.vnaloha.common.model.Paging;
import com.vnaloha.common.model.User;
import com.vnaloha.util.UploadUtil;
import com.vnaloha.util.VnalohaConstant;

@Service
public class GalleryServiceImpl implements GalleryService{
	
	/*
	 * The log
	 */
	private Logger logger = LoggerFactory.getLogger(GalleryServiceImpl.class);
	
	@Autowired
	private GalleryDAO galleryDAO;
	
	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.GalleryService#save(javax.servlet.http.HttpServletRequest, org.springframework.web.multipart.MultipartFile, com.vnaloha.common.model.Gallery)
	 */
	@Override
	@Transactional
	public boolean save(HttpServletRequest request, MultipartFile file, Gallery gallery) {
		
		logger.info("Save gallery: " + gallery + " request: " + request + " file: " + file);
		
		UploadUtil uploadUtil = new UploadUtil();
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		Calendar cal = Calendar.getInstance();
		
		String dir = getDir(request, cal);
		String url = getUrl(request, cal);
		
		String fileType = file.getContentType();
		// create file name
		String fileName = sdf.format(cal.getTime()) + "-" + file.getOriginalFilename();
		String filePath = url + fileName;
		
		// create static user
		User user = new User();
		user.setId(1);
		
		gallery.setFilePath(filePath);
		gallery.setFileType(fileType);
		gallery.setUser(user);
		// first time - item will enable
		gallery.setEnable(1);
		
		return (galleryDAO.save(gallery) && uploadUtil.upload(request, file, dir, fileName));
	}

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.GalleryService#get(int)
	 */
	@Override
	@Transactional
	public Gallery get(int id) {
		
		logger.info("Get gallery by id: " + id);
		return galleryDAO.get(id);
	}

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.GalleryService#list()
	 */
	@Override
	@Transactional
	public List<Gallery> list() {
		
		return galleryDAO.list();
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.GalleryService#list(com.vnaloha.common.model.Paging)
	 */
	@Override
	public List<Gallery> list(Paging paging) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.GalleryService#delete(int)
	 */
	@Override
	@Transactional
	public boolean delete(int id, HttpServletRequest request) {
		
		logger.info("Delete gallery by id: " +id);
		
		Gallery gallery = galleryDAO.get(id);
		// try remove image of gallery in directory
		if(galleryDAO.delete(id)) {
			
			UploadUtil uploadUtil = new UploadUtil();
			
			return uploadUtil.delete(request, gallery.getFilePath());
		}
		
		return false;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.GalleryService#deleteByListId(java.lang.String, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public boolean deleteByListId(String listId, HttpServletRequest request) {
		
		logger.info("delete many record by list id: " + listId + " http request: " + request);
		
		String[] arrId = convertListId(listId);
		int id = 0;
		// loop to delete all
		for(int i = 0; i< arrId.length; i++) {
			// convert to integer
			id = Integer.parseInt(arrId[i]);
			// remove
			if (!delete(id, request)) {
				return false;
			}
		}
		
		return true;
	}
	/*
	 * ==============================================================
	 * ======================= private method =======================
	 * ==============================================================
	 */
	/**
	 * get directory 
	 * @param request http request
	 * @param cal current date
	 * @return a string of directory to save file
	 */
	private String getDir(HttpServletRequest request, Calendar cal) {
		
		logger.info("Get directory to save file " + request + "current date: " + cal);
		int month = cal.get(Calendar.MONTH) + 1;
		String dir = request.getSession().getServletContext().getRealPath("/") + VnalohaConstant.PATH_UPLOAD + "/" + cal.get(Calendar.YEAR) + "/"
					                         + month + "/" 
					                         + cal.get(Calendar.DAY_OF_MONTH) + "/";
		
		return dir;
	}
	
	/**
	 * get url file
	 * @param request http request
	 * @param cal current date
	 * @return a string of url file save in server
	 */
	private String getUrl(HttpServletRequest request, Calendar cal) {
		
		logger.info("Get url to store in database " + request + "current date: " + cal);
		int month = cal.get(Calendar.MONTH) + 1;
		String url = "/" + VnalohaConstant.PATH_UPLOAD + "/" + cal.get(Calendar.YEAR) + "/"
							                + month + "/" 
							                + cal.get(Calendar.DAY_OF_MONTH) + "/";
		
		return url;
	}
	
	/**
	 * Convert listid String to array
	 * @param listId
	 * @return array string if list not null.
	 */
	private String[] convertListId(String listId) {
		//check input
		if(StringUtils.isNotBlank(listId)) {
			
			String[] arr = listId.split(",");
			return arr;
		}
		return null;
	}

	
}
